package com.example.blogsystem.config;

import com.example.blogsystem.service.UserService;
import com.example.blogsystem.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录验证
        //从header中获取token
        String token = request.getHeader("user_token");
        Claims claims = JwtUtils.parseToken(token);
        if(claims == null || userService.getUserById((Integer) claims.get("id")) == null){
            //log.info("请求路径: URL{}", request.getRequestURL().toString());
            response.setStatus(401);
            return false;
        }
        return true;
    }


//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //先从请求中获取session
//        HttpSession session = request.getSession(false);
//        if(session == null || session.getAttribute("SESSION_USER_KEY") == null){
//            //表示用户未登录
//            response.setStatus(401);
//            return false;
//        }
//        return true;
//    }
}
